package com.qianniu.napi.admin.web;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.base.Strings;
import com.qianniu.napi.admin.entity.Health;
import com.qianniu.napi.admin.entity.Jinfo;
import com.qianniu.napi.admin.entity.Store;
import com.qianniu.napi.admin.entity.User;
import com.qianniu.napi.admin.entity.vo.HealthVO;
import com.qianniu.napi.admin.service.IHealthService;
import com.qianniu.napi.admin.service.IRedisService;
import com.qianniu.napi.admin.service.IStoreService;
import com.qianniu.napi.common.util.CardUtil;
import com.qianniu.napi.common.util.DateUtil;
import com.qianniu.napi.common.util.ObjectUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
public class HealthController {

    private static final Logger logger = LoggerFactory.getLogger(HealthController.class);

    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm:ss");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

    @Autowired
    private IHealthService healthService;
    @Autowired
    private IRedisService redisService;
    @Autowired
    private IStoreService storeService;

    @RequestMapping("/api/health/list")
    @ResponseBody
    public Jinfo list(@RequestParam(value = "status", required = false) String status,
                      @RequestParam(value = "pageIndex", required = false) Integer pageIndex,
                      @RequestParam(value = "pageSize", required = false) Integer pageSize,
                      HttpServletRequest req) {
        Jinfo info = new Jinfo();
        if (pageSize == null) pageSize = 10;
        Page page = new Page(pageIndex, pageSize);
        page = healthService.selectPage(page, new EntityWrapper<Health>()
                .eq("uid", ObjectUtil.getUid())
                .eq("state", 1));
        info.setInfo(page.getRecords());
        return info;
    }

    @RequestMapping("/api/health/jklist")
    @ResponseBody
    public Jinfo jklist(@RequestParam(value = "vid", required = false) Long uid,
                        @RequestParam(value = "pageIndex", required = false) Integer pageIndex,
                        @RequestParam(value = "pageSize", required = false) Integer pageSize,
                        HttpServletRequest req) {
        Jinfo info = new Jinfo();
        if (uid == null) uid = ObjectUtil.getUid();
        if (uid == null) {
            info.setCode(1);
            info.setMsg("参数有误");
            return info;
        }
        if (pageSize == null) pageSize = 40;

        Page page = new Page(pageIndex, pageSize);
        page = healthService.selectPage(page, new EntityWrapper<Health>()
                .eq("uid", uid).orderBy("id", false));

        List<Health> records = page.getRecords();
        List<HealthVO> list = new ArrayList<HealthVO>();
        Map<String, List<Health>> map = new HashMap<String, List<Health>>();

        boolean first = true;
        String lastday = null;
        String day = null;
        for (Health item : records) {
            item.setStatday(item.getStatday().substring(5));
            day = item.getStatday();
            if (map.containsKey(day)) {
                map.get(item.getStatday()).add(item);

            } else {
                List<Health> mplist = new ArrayList<Health>();
                mplist.add(item);
                map.put(day, mplist);
                if (!first) {
                    HealthVO healthVO = new HealthVO();
                    healthVO.setStatday(lastday);
                    healthVO.setHealths(map.get(lastday));
                    list.add(healthVO);
                }
            }
            first = false;
            lastday = day;
        }
        if (lastday != null) {
            HealthVO healthVO = new HealthVO();
            healthVO.setStatday(lastday);
            healthVO.setHealths(map.get(lastday));
            list.add(healthVO);
        }
        User user = redisService.getUser(uid);
        info.setInfo(list);
        info.setData(user);
        return info;
    }

    @RequestMapping("/api/health/add")
    @ResponseBody
    public Jinfo healthAdd(Health bean
            , @RequestParam(value = "province", required = false) String province
            , @RequestParam(value = "city", required = false) String city
            , @RequestParam(value = "district", required = false) String district
            , @RequestParam(value = "vid", required = false) Long vid) {
        Jinfo info = new Jinfo();
        if (ObjectUtil.getUid() == null) {
            info.setCode(1);
            info.setMsg("请授权登录后再操作");
            return info;
        }
        //字段校验
        if (bean.getType() == null) bean.setType(0);
        // type:统计类型@0：信息录入；1：打卡(一天一次)；2：进出登记
        if (bean.getType() == 0) {
            User nuser = new User();
            nuser.setId(ObjectUtil.getUid());
            nuser.setName(bean.getName());

//            nuser.setCardno(bean.getCardno());

            nuser.setAddress(bean.getAddress());
            nuser.setLatitude(bean.getLatitude());
            nuser.setLongitude(bean.getLongitude());

//            nuser.setCompany(bean.getCompany());
            nuser.setSex(bean.getSex());
            nuser.setAge(bean.getAge());

            nuser.setProvince(province);
            nuser.setCity(city);
            nuser.setCountry(district);

            nuser.setModifytime(new Date());
            nuser.updateById();

            redisService.delUser(ObjectUtil.getUid());
        } else {
            if (!Strings.isNullOrEmpty(bean.getCardno()) && (bean.getSex() == null || bean.getAge() == null)) {
                try {
                    Map<String, Integer> map = CardUtil.getCarInfo(bean.getCardno());
                    if (map.containsKey("age")) bean.setAge(map.get("age"));
                    if (map.containsKey("sex")) bean.setSex(map.get("sex"));
                } catch (Exception e) {

                }
            }
            if(Strings.isNullOrEmpty(bean.getPhone())){
                User user = redisService.getUser();
                bean.setPhone(user.getPhone());
            }
        }
        logger.debug("========================================api/health/add statday=" + DateUtil.getToday("YYYY-MM-dd"));

        bean.setStatday(DateUtil.getToday("YYYY-MM-dd"));
        logger.debug("========================================api/health/add bean.getStatday=" + bean.getStatday());

        bean.setCreatetime(new Date());
        bean.setMpid(ObjectUtil.getMpid());
        bean.setUid(ObjectUtil.getUid());
        if (bean.getType() == 2) {
            bean.setUid(vid==null?ObjectUtil.getUid():vid);
        }
        logger.debug("========================================api/health/add bean=" + JSON.toJSONString(bean));
        bean.insert();

        if (bean.getType() == 0 && bean.getSid()!=null) {
            Store store = storeService.selectById(bean.getSid());
            bean.setId(null);
            bean.setType(2);
            bean.setAddress(store.getAddress());
            bean.setSname(store.getName());
            bean.setIotype(1);//进入
            bean.insert();
        }

        return info;
    }

    @RequestMapping("/api/health/modify")
    @ResponseBody
    public Jinfo healthUpdate(Health bean) {
        Jinfo info = new Jinfo();
        bean.updateById();
        return info;
    }

    // type:统计类型@0：信息录入；1：打卡(一天一次)；2：进出登记
    @RequestMapping("/api/health/detail")
    @ResponseBody
    public Jinfo getHealthDetailById(@RequestParam("token") String token,
                                     @RequestParam("id") long id, HttpServletRequest req
    ) {
        Jinfo info = new Jinfo();
        Long uid = ObjectUtil.getUid();
        Health base = healthService.selectOne(new EntityWrapper<Health>()
                .eq("type", 0)
                .eq("uid", uid)
                .eq("mpid", ObjectUtil.getMpid()));
        info.setInfo(base);
        Health daka = healthService.selectOne(new EntityWrapper<Health>()
                .eq("type", 1)
                .eq("uid", uid)
                .eq("mpid", ObjectUtil.getMpid()));
        info.setData(daka);
        return info;
    }

}
